package com.lyq.login.service.impl;

import com.lyq.login.constant.LoginConstant;
import com.lyq.login.dto.LoginDTO;
import com.lyq.login.service.ILoginService;
import com.lyq.org.domain.Employee;
import com.lyq.org.service.IEmployeeService;
import com.lyq.basic.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

/**
 * @Author:liangyunqian
 * @Date: 2022/12/18  20:18
 * @Description:
 */
@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private IEmployeeService employeeService;

    @Override
    public R login(LoginDTO dto) {

        String username = dto.getUsername();
        String password = dto.getPassword();

        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            throw new RuntimeException("用户名或密码不能为空!!!请检查后重新提交");
        }

        Employee employee = employeeService.getByUsername(username);

        if(Objects.isNull(employee)){
            throw new RuntimeException("用户名或密码错误!请检查后重新提交!");
        }

        if(!password.equals(employee.getPassword())){
            throw new RuntimeException("用户名或密码错误!请检查后重新提交!");
        }

        String token = UUID.randomUUID().toString();

        LoginConstant.loginMap.put(token,employee);

        Map<String,Object> resultMap = new HashMap<>();

        resultMap.put("token",token);
        employee.setPassword("");
        resultMap.put("loginUser",employee);


        return R.me().setData(resultMap);
    }
}
